package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.exception.LogicalException;
import cn.wolfcode.wolf2w.query.RegionQueryObject;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.PagingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
//@Transactional
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public void save(Region region) {
        region.setId(null);   //设为空值,防止数据库不会自动创建id
        repository.save(region);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);

    }

    @Override
    public void update(Region region) {
        repository.save(region);
    }

    @Override
    public Region get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return repository.findAll();
    }

    @Override
    public Page<Region> query(RegionQueryObject qo) {

        //查询封装类
        Query query = new Query();

        //查询分页
         Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        //调用工具方法,返回分页数据
        return PagingUtil.query(query, template, Region.class, pageable);

    }

    @Override
    public void saveOrUpdate(Region region) {
        //判断是否有id
        if (StringUtils.hasLength(region.getId())){
            //这里是全量更新
            this.update(region);
        }else {
            this.save(region);
        }
    }

    @Override
    public void changeHotValue(int hot, String id) {
        //校验参数
        if (!StringUtils.hasLength(id)){
            throw new LogicalException("参数异常");
        }
        //方式1
        /*//查询区域对象
        Region region = this.get(id);
        //设置热门
        region.setIshot(hot);
        //更新数据
        this.update(region);*/

        //方式2
        //条件拼接对象
        Query query = new Query();
        //封装条件
        query.addCriteria(Criteria.where("_id").is(id));
        //新建更新类
        Update update = new Update();
        //设置更新数据
        update.set("ishot", hot);
        //执行更新
        template.updateMulti(query, update, Region.class);

    }

    @Override
    public List<Region> getHotRegion() {

        List<Region> regions = repository.findByIshotOrderBySequence(1);
        return regions;
    }


}
